﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FC8280TServer.WebSocket
{
    public class ChatWebSocketMiddleware : WebsocketMiddlewareBase
    {
        private static ConcurrentDictionary<string, SocketContext> _sockets = new ConcurrentDictionary<string, SocketContext>();

        private readonly RequestDelegate _next;

        private string _socketId;
        public ChatWebSocketMiddleware(ILogger<ChatWebSocketMiddleware> logger, RequestDelegate next)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next.Invoke(context);
                return;
            }
            if (context.Request.Path != "/message")
            {
                await _next.Invoke(context);
                return;
            }

            var mySocket = await ConnectClient(context);





            _socketId = context.Request.Query["sid"].ToString();
            if (!string.IsNullOrWhiteSpace(_socketId) && !_sockets.ContainsKey(_socketId))
            {
                _sockets.TryAdd(_socketId, mySocket);
            }
            else
            {
                await CloseConnect(mySocket);//终止了
                return;
            }

            //开始运行基础逻辑
            await Run(mySocket, ResponseMessage);



            _sockets.TryRemove(_socketId, out mySocket);
            mySocket = null;


        }

        public async Task ResponseMessage(SocketContext sendSocket, string sMessage)
        {
            try
            {
                WebsocketMsgTemplate msg = JsonConvert.DeserializeObject<WebsocketMsgTemplate>(sMessage);
                foreach (var socket in _sockets)
                {
                    if (socket.Value.CurrentSocket.State != WebSocketState.Open)
                    {
                        continue;
                    }
                    if (socket.Key == msg.ReceiverID)
                    {
                        await SendStringAsync(socket.Value.CurrentSocket, JsonConvert.SerializeObject(msg), socket.Value.SocketCancellationToken);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("ChatWebSocketMiddleware.ResponseMessage -- " + ex.Message);
            }
        }

    }
}
